namespace Warehouse

open System.Collections.ObjectModel

open FSharp.Windows

type ProductSearchChildController(?repository) = 
    inherit Controller<ProductSearchEvents, ProductSearchModel>()

    let repository = defaultArg repository (new DataModel.Repository())

    override this.InitModel model = 
        model.IsSearchInProgress <- false
        model.Products <- ObservableCollection.empty

    override this.Dispatcher = function
        | Search -> Sync this.Search

    member this.Search model = 
        model.IsSearchInProgress <- true
        model.Products <- 
            seq {
                for p in repository.ProductsByFilter model.Filter do
                    let product : ProductModel = EntityModel.Load p
                    for upc in product.UPCs do
                        upc.Quantity <- repository.AvailableQuantityByUPC upc.Entity
                    product.Compute()
                    yield product
            }
            |> Seq.filter model.AppFilter
            |> ObservableCollection.ofSeq 
        model.IsSearchInProgress <- false



